import storage from "./storage";
import queue from "./queue";

/** 请求模块 */

function request_init_all(params) {
    for (let key in request) {
        if (key === "init_all" || key === "fetch") {
            continue;
        }
        request[key](params);
    }
}

//内部请求上报
function request_fetch() {
    let param = queue.queue.shift();
    let reportingBefore = storage.config_info.reportingBefore;
    if (!storage.config_info.sendAddress) {
        //如果未配置发送地址，则停止消息推送队列
        console.warn("[logjs] The reporting address has not been configured. ");
        queue.shutdown();
        return void 0;
    }
    if (!param) return void 0;

    if (reportingBefore && typeof reportingBefore === "function") {
        param = reportingBefore(param) || param;
    }

    fetch(storage.config_info.sendAddress, {
            headers: {
                "Content-Type": "application/json;charset=UTF-8"
            },
            method: "POST",
            body: JSON.stringify(param)
        },
        true
    ).then(function (res) {
        //
    });
}

function cover_fetch(params) {
    let oldFetch = window.fetch;
    let newFetch = function (url, options, isLogJs) {
        return oldFetch(url, options);
    };
    window.fetch = newFetch;
}

let request = {
    cover_fetch: cover_fetch, //复写 fetch 实现
    fetch: request_fetch, //内部 fetch 请求
    init_all: request_init_all, //初始化所有请求模块
};

export default request;